import React,{Component} from 'react'
import { connect } from 'dva'
import router from 'umi/router'
import { Col, Form, Icon, Input,Button} from 'antd';
const FormItem = Form.Item;
class LoginInput extends Component {
  constructor(props) {
    super(props)
  }
  state = {
    userName: ''
  }
  hasErrors= (fieldsError) => {
    return Object.keys(fieldsError).some(field => fieldsError[field]);
  }
  handInput = (e) => {
    console.log(11)
    this.setState({
      userName: window[e.target.name].value
    })
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if(!err) {
        console.log(values)
        // console.log(values)
        // this.props.dispatch({
        //   type:'loginInput/login',
        //   user:{
        //     ...values
        //   }
        // })
        this.props.dispatch({
          type:'global/setName',
          user:{
            ...values
          }
        })
        router.push(
          '/user'
        )
      }
    })
  }
  componentDidMount() {
    this.props.form.validateFields();
    console.log(this.props)
  }

  render() {
    const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
    const userNameError = isFieldTouched('userName') && getFieldError('userName');
    const passwordError = isFieldTouched('password') && getFieldError('password')
    return(
      <div>
        <Col span={12}>
          <Form layout="vertical" onSubmit={this.handleSubmit}>
            <FormItem validateStatus={userNameError ? 'error' : ''} help={userNameError || ''}>
              {getFieldDecorator('userName', {
                rules: [{required: true, message: 'plase input your username'}]
              })(
                <Input name="userName" id="userName" prefix={<Icon type="user" style={{color:'rgba(0,0,0,.25)'}}></Icon>} placeholder="userName" onChange={this.handInput}/>
              )}
            </FormItem>
            <FormItem validateStatus={passwordError ? 'error' : ''} help={passwordError || ''}>
              {getFieldDecorator('password', {
                rules: [{required: true, message: 'plase input your password'}]
              })(
                <Input prefix={<Icon type="lock" style={{color:'rgba(0,0,0,.25)'}}></Icon>} placeholder="password"/>
              )}
            </FormItem>
            <FormItem>
              <Button type="primary" htmlType="submit" disabled={this.hasErrors(getFieldsError())}></Button>
            </FormItem>
          </Form>
        </Col>
        <span>用户名：{this.state.userName}</span>
      </div>
    )
  }
}
const WrappedInput = Form.create()(LoginInput)
export default connect(({global}) => ({
  user: global.user
}))(WrappedInput)